package com.xjuse.yida.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjuse.yida.commom.ConstantEnum;
import com.xjuse.yida.commom.jwt.JwtUser;
import com.xjuse.yida.commom.jwt.interceptor.AuthStorage;
import com.xjuse.yida.commom.util.Result;
import com.xjuse.yida.dto.UserClothesRespDto;
import com.xjuse.yida.entity.Cloth;
import com.xjuse.yida.entity.UserClothes;
import com.xjuse.yida.entity.UserInfo;
import com.xjuse.yida.mapper.ClothesMapper;
import com.xjuse.yida.mapper.UserClothesMapper;
import com.xjuse.yida.mapper.UserInfoMapper;
import com.xjuse.yida.service.ClothesService;
import com.xjuse.yida.service.UserClothesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.xjuse.yida.commom.ConstantEnum.OTHER;

/**
 *  用户衣物信息服务实现类
 *
 * @author duwx
 * @since 2022-10-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserClothesServiceImpl extends ServiceImpl<UserClothesMapper, UserClothes> implements UserClothesService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserClothesMapper userClothesMapper;
    @Autowired
    private ClothesService clothesService;
    @Autowired
    private ClothesMapper clothesMapper;

    @Override
    public Result insertUserClothes(UserClothes userClothes) {
        String userId = userClothes.getUserId();
        //未传入UserId就从全局Jwt用户中取
        if (userId==null|| StringUtils.isEmpty(userId)){
            JwtUser user = AuthStorage.getUser();
            if (user==null||StringUtils.isEmpty(user.getUserId())){
                return Result.failed("请先登录!");
            }
            userId=user.getUserId();
        }
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Cloth cloth = clothesMapper.selectById(userClothes.getClothId());
        userClothes.setClothType(cloth.getClothName());
        userClothes.setUserId(userId);
        userClothes.setUserName(userInfo.getUserName());
        //todo 注意：保暖度给定范围，由用户手动录入
        userClothes.setClothWarm(25);
        userClothes.setAddTime(LocalDateTime.now());
        boolean result = this.save(userClothes);
        return result? Result.ok(userClothes,"录入成功!"):Result.failed("录入失败，请重试");
    }

    @Override
    public Result findClothesByUser() {
        JwtUser user = AuthStorage.getUser();
        if (user==null||StringUtils.isEmpty(user.getUserId())){
            return Result.failed("请先登录!");
        }
        String userId = user.getUserId();
        QueryWrapper<UserClothes> wrapper = new QueryWrapper<UserClothes>().eq("user_id", userId);
        List<UserClothes> userClothes = userClothesMapper.selectList(wrapper);
        //获取到所有衣物分类信息列表    每次都将所有衣物的种类和数量等具体信息包装
        List<Cloth> clothes = clothesService.queryClothesList();
        ArrayList<UserClothesRespDto.UserTypeClothes> userTypeClothes = new ArrayList<>(16);
        clothes.forEach(cloth->{
            UserClothesRespDto.UserTypeClothes typeClothes = UserClothesRespDto.UserTypeClothes.builder()
                    .clothesId(cloth.getClothId())
                    .clothesType(cloth.getClothName())
                    .userClothesList(new ArrayList<>()).build();
            userClothes.forEach(userCloth->{
                if (cloth.getClothId().equals(userCloth.getClothId())){
                    typeClothes.getUserClothesList().add(userCloth);
                }
            });
            typeClothes.setClothCount(typeClothes.getUserClothesList().size());
            userTypeClothes.add(typeClothes);
        });
        UserClothesRespDto respDto = UserClothesRespDto.builder()
                .data(userTypeClothes)
                .time(LocalDateTime.now()).build();
        return Result.ok(respDto);
    }


    @Override
    public Map<String, List<UserClothes>> clothByRecomType(String userId) {
        List<ConstantEnum> recomTypeEnums = ConstantEnum.getEnumsByCode(OTHER.getCode());
        HashMap<String, List<UserClothes>> map = new HashMap<>();
        //按穿搭推荐分类 获取用户衣物信息
        recomTypeEnums.forEach(type->{
            String clothType = (String)type.getData();
            String typeName = type.getStr();
            QueryWrapper<Cloth> wrapper = new QueryWrapper<Cloth>().eq("cloth_type",clothType);
            List<String> list = clothesMapper.selectList(wrapper).stream().map(Cloth::getClothName).collect(Collectors.toList());

            QueryWrapper<UserClothes> wrapper1 = new QueryWrapper<UserClothes>().eq("user_id", userId);
            List<UserClothes> userClothes = userClothesMapper.selectList(wrapper1);
            List<UserClothes> clothes = userClothes.stream().filter(cloth -> list.contains(cloth.getClothType())).collect(Collectors.toList());
            map.put(typeName,clothes);
        });
        Assert.isTrue(map.size()==4,"获取到的用户穿搭衣物分类信息异常！");
        return map;
    }

    @Override
    public List<UserClothes> clothesByUserAndClothIds(String userId, String clothesIds) {
        List<String> list = Arrays.asList(clothesIds.split(","));
        QueryWrapper<UserClothes> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.in("cloth_id", list);
        return userClothesMapper.selectList(wrapper);
    }
}
